package com.xindaoapp.happypet.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BaiDuLocationManager;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.iflytek.voice.JsonParser;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.rockerhieu.emojicon.EmojiconHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.AddPetActivity;
import com.xindaoapp.happypet.activity.PictureEditorActivity;
import com.xindaoapp.happypet.activity.PictureListActivity;
import com.xindaoapp.happypet.adapter.NotePictureAdapter;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.PetInfo;
import com.xindaoapp.happypet.bean.PetInfo.Pet;
import com.xindaoapp.happypet.bean.SplashPictureBean.SplashBannerInfo;
import com.xindaoapp.happypet.bean.TagInfos;
import com.xindaoapp.happypet.bean.TagInfos.TagInfo;
import com.xindaoapp.happypet.entry.Location;
import com.xindaoapp.happypet.protocol.IUploadProgress;
import com.xindaoapp.happypet.protocol.PostQueue;
import com.xindaoapp.happypet.protocol.PostQueueImpl;
import com.xindaoapp.happypet.ui.QuoteVideoActivity.VIDEO_TYPE;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.Constants.PUBLISHPOSTS;
import com.xindaoapp.happypet.utils.Expressions;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.KeyValuePair;
import com.xindaoapp.happypet.utils.MoccaPreferences;
import com.xindaoapp.happypet.view.FixGridLayout;
import com.xindaoapp.happypet.weight.AutoMeasureGridView;
import com.xindaoapp.share.SharePopupWindow;
import com.yixia.camera.demo.ui.record.MediaRecorderActivity;

/**
 * 发帖界面
 * 
 * @author chenghao
 * 
 */
public class PostMessageActivity extends BaseActivity implements OnClickListener {

    private static final int BAIDULOATIONRESULT = 12;
    /** 工具栏引用布局 */
    private View vFunctionContainerView;
    /** 图片引用布局 */
    private AutoMeasureGridView vPictureGridView;
    /** 视频引用布局 */
    private View vFunctionVideoInfo;
    /** 帖子引用布局 */
    private View vFunctionQuotePostInfo;
    /** 录制的视频 */
    private View vRecordVideoView;
    private EditText vTitle;
    private EditText vContent;
    // private LinearLayout vUserFaceContainer;
    private View vShareToSina;
    /** 表情按钮区域 */
    private LinearLayout vPlanPoint;
    private ViewPager vViewPager;
    private ImageView vFaceView;
    private View vHideInputView;
    /** 表情区域布局 */
    private View vFaceContainerView;
    private View vFaceAllViews;
    /** 选择宠物的窗口 */
    private LinearLayout mSelectPetContainer;
    private TextView vTags;
    private FixGridLayout vTagsContainer;
    // private LinearLayout vTagsContainer;

    /** 图片适配器 */
    private NotePictureAdapter mNotePictureAdapter;
    private String mCameraFilePath;
    private PostQueue mPostQueueImpl;
    /** 俱乐部fid */
    private String mForumId = "";
    private String mPostTitle = "";
    private String mPostContent = "";
    private RecordVideoReceiver mRecordVideoReceiver;
    private TagInfos mTagInfos;
    private String mTags = "";

    // 语音听写对象
    // private SpeechRecognizer mIat;
    /** 来源于活动 */
    private boolean isFromActivity;

    private RecognizerDialog iatDialog;
    private BaiDuLocationManager locationManager;
    // private Location location;
    private JSONObject jo = null;
    boolean isPostMessage = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTopBarTitle("发帖");
        CommonUtil.mkFiledir(Environment.getExternalStorageDirectory().getPath() + "happypet/pic");

        locationManager = BaiDuLocationManager.getInstance(PostMessageActivity.this);

        mRecordVideoReceiver = new RecordVideoReceiver();
        registerReceiver(mRecordVideoReceiver, new IntentFilter("record_video_finish"));

        // 初始化识别对象
        // mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
        // iatDialog = new RecognizerDialog(this, mInitListener);
    }

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_send_post;
    }

    @Override
    protected void initViews() {
        super.initViews();
        vTagsContainer = (FixGridLayout) findViewById(R.id.l_users);
        mSelectPetContainer = (LinearLayout) findViewById(R.id.select_pet);
        vRecordVideoView = findViewById(R.id.record_video);
        vRecordVideoView.setOnClickListener(this);
        vFaceAllViews = findViewById(R.id.post_bottom_tab_view);
        vFaceContainerView = findViewById(R.id.face);
        vFaceView = (ImageView) findViewById(R.id.show_faceview);
        vHideInputView = findViewById(R.id.hide_key);
        vViewPager = (ViewPager) findViewById(R.id.viewpager);
        vPlanPoint = (LinearLayout) findViewById(R.id.page_select);
        vShareToSina = findViewById(R.id.share_to_sina);

        locationText = (TextView) findViewById(R.id.location);
        image_icon = (ImageView) findViewById(R.id.image_icon);

        if (MoccaPreferences.SINA_WEIBO_LOGIN_STATE.get()
                && new SharePopupWindow().isAuthenticatedBySina(getBaseContext())) {
            vShareToSina.setSelected(true);
        }

        // vUserFaceContainer = (LinearLayout) findViewById(R.id.l_users);
        vTitle = (EditText) findViewById(R.id.title);
        vContent = (EditText) findViewById(R.id.content);
        vFunctionContainerView = findViewById(R.id.function);
        vFunctionVideoInfo = findViewById(R.id.video_info);
        vFunctionQuotePostInfo = findViewById(R.id.quote_post_info);
        vPictureGridView = (AutoMeasureGridView) findViewById(R.id.gridview);
        vTags = (TextView) findViewById(R.id.quote_friend);

        ArrayList<String> list = new ArrayList<String>();
        if (getIntent().hasExtra(Constants.PARAM_PHOTO_LIST)) {
            list = getIntent().getStringArrayListExtra(Constants.PARAM_PHOTO_LIST);
        }

        if (getIntent().hasExtra(Constants.KEY_CAMERA_PICTURE_PATH)) {
            list.add(getIntent().getStringExtra(Constants.KEY_CAMERA_PICTURE_PATH));
        }

        mNotePictureAdapter = new NotePictureAdapter(getBaseContext(), new ArrayList<String>());
        vPictureGridView.setAdapter(mNotePictureAdapter);

        mForumId = getIntent().getStringExtra(Constants.KEY_GROUP_FID);

        mPostQueueImpl =
                new PostQueueImpl(this, UserState.getUserUid(), mForumId,
                        System.currentTimeMillis(), iUploadProgress);



        if (list.size() > 0) {
            handlePickPhotos(list);
        }

        initFaceView();
        initTags();
        mForumId = getIntent().getStringExtra(Constants.KEY_GROUP_FID);
        if (TextUtils.isEmpty(mForumId)) {
            initPets();
        } else {
        }

        // 隐藏视频和引用帖子
        if (isFromActivity) {
            findViewById(R.id.function_activity).setVisibility(View.VISIBLE);
            findViewById(R.id.function_no_activity).setVisibility(View.GONE);
        } else {
            findViewById(R.id.function_activity).setVisibility(View.GONE);
            findViewById(R.id.function_no_activity).setVisibility(View.VISIBLE);
        }

    }

    SplashBannerInfo mSplashBannerInfo;

    private void initTags() {
        if (getIntent().hasExtra(Constants.KEY_SHAITUINFO)) {
            isFromActivity = true;
            mSplashBannerInfo =
                    (SplashBannerInfo) getIntent().getSerializableExtra(Constants.KEY_SHAITUINFO);
            TagInfo tagInfo = new TagInfo();
            tagInfo.tagid = mSplashBannerInfo.tagid;
            tagInfo.tagname = mSplashBannerInfo.tag;
            mTagList.add(tagInfo);
            resetTags(mTagList);
        }
        getMoccaApi().getMyTags(new IRequest<TagInfos>() {

            @Override
            public void request(TagInfos t) {
                mTagInfos = t;
            }
        });
    }

    private int mPetPostion = -1;

    /**
     * 初始化宠物列表
     */
    private void initPets() {

        if (UserState.getPetInfo() == null) {
            PetInfo petInfo = new PetInfo();
            petInfo.setArray(new ArrayList<PetInfo.Pet>());
            UserState.setPetInfo(petInfo);
            findViewById(R.id.h_select_pet).setVisibility(View.GONE);
            findViewById(R.id.l_addpet).setVisibility(View.VISIBLE);
            return;
        } else if (UserState.getPetInfo().getArray() == null) {
            PetInfo petInfo = UserState.getPetInfo();
            petInfo.setArray(new ArrayList<PetInfo.Pet>());
            findViewById(R.id.h_select_pet).setVisibility(View.GONE);
            findViewById(R.id.l_addpet).setVisibility(View.VISIBLE);
            return;
        } else if (UserState.getPetInfo().getArray().size() == 0) {
            findViewById(R.id.h_select_pet).setVisibility(View.GONE);
            findViewById(R.id.l_addpet).setVisibility(View.VISIBLE);
            return;
        } else {
            findViewById(R.id.h_select_pet).setVisibility(View.VISIBLE);
            findViewById(R.id.l_addpet).setVisibility(View.GONE);
        }

        mSelectPetContainer.removeAllViews();
        for (int i = 0; i < UserState.getPetInfo().getArray().size(); i++) {
            final Pet info = UserState.getPetInfo().getArray().get(i);
            View view = View.inflate(getBaseContext(), R.layout.item_pet, null);
            final View ticked = view.findViewById(R.id.ticked);
            final int temp = i;

            if (i == 0) {
                mPetPostion = 0;
                ticked.setVisibility(View.VISIBLE);
            }

            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (mPetPostion == temp) {
                        return;
                    }
                    if (ticked.getVisibility() == View.VISIBLE) {
                        mPetPostion = -1;
                        ticked.setVisibility(View.GONE);
                    } else {
                        if (mPetPostion != -1) {
                            mSelectPetContainer.getChildAt(mPetPostion).findViewById(R.id.ticked)
                                    .setVisibility(View.GONE);
                        }
                        mPetPostion = temp;
                        ticked.setVisibility(View.VISIBLE);
                    }
                }
            });

            ImageLoader.getInstance().displayImage(info.getCover(),
                    (ImageView) view.findViewById(R.id.icon));
            mSelectPetContainer.addView(view);
        }
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        vFaceView.setOnClickListener(this);
        vHideInputView.setOnClickListener(this);
        vShareToSina.setOnClickListener(this);
        findViewById(R.id.show_aite).setOnClickListener(this);
        findViewById(R.id.photo).setOnClickListener(this);
        findViewById(R.id.photo_activity).setOnClickListener(this);
        findViewById(R.id.video).setOnClickListener(this);
        findViewById(R.id.quote_post).setOnClickListener(this);
        findViewById(R.id.voice_input).setOnClickListener(this);
        findViewById(R.id.showLocation).setOnClickListener(this);
        vTags.setOnClickListener(this);
        findViewById(R.id.add_pet).setOnClickListener(this);
        vPictureGridView.setOnItemClickListener(mOnItemClickListener);
        vContent.setOnTouchListener(mContentOnTouchListener);
        vContent.addTextChangedListener(mContentTextWatcher);
        vContent.setFocusable(true);
        vTitle.setOnTouchListener(mTitleOnTouchListener);
        vTitle.addTextChangedListener(mTitleTextWatcher);

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mRecordVideoReceiver);
        locationManager.stopLocation();
        // 退出时释放连接
        // if (mIat != null) {
        // mIat.cancel();
        // mIat.destroy();
        // }
        System.gc();


    }

    private final OnTouchListener mTitleOnTouchListener = new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                vFaceAllViews.setVisibility(View.GONE);
                vFaceContainerView.setVisibility(View.GONE);
            }
            return false;
        }
    };
    private final OnTouchListener mContentOnTouchListener = new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                vFaceAllViews.setVisibility(View.VISIBLE);
                vFaceContainerView.setVisibility(View.GONE);
            }
            return false;
        }
    };
    private final TextWatcher mTitleTextWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(s.toString())) {
                mPostTitle = "";
                return;
            }
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}

        @Override
        public void afterTextChanged(Editable arg0) {
            mPostTitle = EmojiconHandler.getMEmojiCode();
        }
    };

    private final TextWatcher mContentTextWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(s.toString())) {
                mPostContent = "";
                return;
            }
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}

        @Override
        public void afterTextChanged(Editable arg0) {
            mPostContent = EmojiconHandler.getMEmojiCode();
        }

    };

    @Override
    protected void onLoadDatas() {
        super.onLoadDatas();
        // ImageLoader.getInstance().displayImage(
        // getIntent().getStringExtra(Constants.KEY_GROUP_ICON),
        // (ImageView) findViewById(R.id.icon));
        // ((TextView) findViewById(R.id.group_name)).setText(getIntent().getStringExtra(
        // Constants.KEY_GROUP_NAME));
        // ((TextView) findViewById(R.id.group_member)).setText(String.format("圈成员：%s人", getIntent()
        // .getStringExtra(Constants.KEY_GROUP_MEMBER)));
    }

    private final OnItemClickListener mOnItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // 通过判断点击的位置是否等于图片的数据
            if (mNotePictureAdapter.getDatas().size() == position) {
                showSelectPicPopupWindow();
            } else {
                // 进入编辑页面
                Intent intent = new Intent(getBaseContext(), PictureEditorActivity.class);
                intent.putStringArrayListExtra(Constants.PARAM_PHOTO_LIST,
                        mNotePictureAdapter.getDatas());
                intent.putExtra(Constants.PARAM_PHOTO_POSITION, position);
                // Intent intent = new Intent(getBaseContext(), ImageFilter2Activity.class);
                // intent.putExtra("image", "file://" +
                // mNotePictureAdapter.getDatas().get(position));
                startActivityForResult(intent, PUBLISHPOSTS.PHOTO_AMEND);
            }
        }
    };
    private final IUploadProgress iUploadProgress = new IUploadProgress() {

        @Override
        public void success() {
            Intent intent = new Intent();
            intent.setAction(Constants.KEY_SEND_POST_SUCCESS);
            getBaseContext().sendBroadcast(intent);
        }

        @Override
        public void start(int current, int count) {}

        @Override
        public void progress(int progress) {}

        @Override
        public void pause() {}

        @Override
        public void error(String msg) {
            Toast toastText = Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT);
            if (CommonUtil.isNetworkAvailable(PostMessageActivity.this) == 0) {
                toastText.setText("网络连接已断开，请检查您的网络连接后重试！");
            } else if (TextUtils.isEmpty(msg)) {
                toastText.setText("发送失败，已将帖子保存到您的草稿箱");
            } else {
                toastText.setText(msg);
            }
            toastText.show();
        }

        @Override
        public void cancel() {}
    };

    @Override
    protected OnClickListener getRightViewClickListener() {
        return new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // 发表
                if (checkInput()) {
                    if (CommonUtil.checkNetState(PostMessageActivity.this)) {
                        if (CommonUtil.isFastDoubleClick2()) {
                            getTopBarRightImageView().setEnabled(false);
                        } else {
                            getTopBarRightImageView().setEnabled(true);
                        }
                        post();
                    } else {
                        Toast.makeText(PostMessageActivity.this,
                                getResources().getString(R.string.net_error), Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            }
        };
    }

    private void post() {
        // 准备发帖前信息
        isPostMessage = true;
        List<KeyValuePair<String, Integer>> list = preparePostMessage();
        // mPostQueueImpl.setFid(UserState.getPetInfo().getArray().get(mPetPostion).getBreedid(),
        // mTags);
        mPostQueueImpl.addQueue(mPostTitle, mPostContent,
                vRecordVideoView.getVisibility() == View.VISIBLE ? null : list, vRecordVideoView
                        .getVisibility() == View.VISIBLE ? true : false,
                jo == null ? "" : jo.toString(), vShareToSina.isSelected() ? 1 : 0);
        mPostQueueImpl.finishActivity(PostMessageActivity.this);
        // if (getIntent().getBooleanExtra(Constants.KEY_START_FROM_SELECT_GROUP, false)) {
        // Intent intent = new Intent(this, MyClubActivity.class);
        // intent.putExtra("name", getIntent().getStringExtra(Constants.KEY_GROUP_NAME));
        // intent.putExtra("fId", UserState.getPetInfo().getArray().get(mPetPostion).getBreedid());
        // startActivity(intent);
        // }
        setResult(RESULT_OK);
        // finish();
        // overridePendingTransition(R.anim.tran_in, R.anim.tran_out);
    }



    /**
     * 准备发帖前信息
     * 
     * @return
     */
    private List<KeyValuePair<String, Integer>> preparePostMessage() {
        HappyPetApplication.get().getUploaQueueImpl().addQueue(mPostQueueImpl);

        List<KeyValuePair<String, Integer>> list = new ArrayList<KeyValuePair<String, Integer>>();
        // 组装图片
        for (int i = 0; i < mNotePictureAdapter.getDatas().size(); i++) {
            list.add(new KeyValuePair<String, Integer>(new File(mNotePictureAdapter.getDatas().get(
                    i)).getAbsolutePath(), new File(mNotePictureAdapter.getDatas().get(i))
                    .getAbsolutePath().lastIndexOf(".mp4") >= 0 ? 1 : 0));
        }


        if (vFunctionVideoInfo.getVisibility() == View.VISIBLE) {// 引用视频
            Intent data = (Intent) vFunctionVideoInfo.getTag();
            if (null != data) {
                try {
                    jo = new JSONObject();
                    jo.put("title", data.getStringExtra(Constants.KEY_VIDEO_NAME));
                    jo.put("body", data.getStringExtra(Constants.KEY_VIDEO_DESCRIPTION));
                    jo.put("url", data.getStringExtra(Constants.KEY_VIDEO_URL));
                    jo.put("coverpath", data.getStringExtra(Constants.KEY_VIDEO_IMAGE_URL));
                } catch (Exception e) {
                }
            }
        }

        if (vFunctionQuotePostInfo.getVisibility() == View.VISIBLE) {// 引用帖子
            Intent data = (Intent) vFunctionQuotePostInfo.getTag();
            if (null != data) {
                mPostContent +=
                        String.format("[appquotethread]%s[/appquotethread]",
                                data.getStringExtra(Constants.KEY_POST_TID));
            }
        }

        for (String username : mFansUser) {
            mPostContent += String.format("@%s ", username);
        }

        mPostContent = CommonUtil.replaceAllKuoHao(mPostContent);
        // Toast.makeText(getBaseContext(), "测试期间，只发420", Toast.LENGTH_SHORT).show();

        if (!"所在位置".equals(locationText.getText().toString())) {
            mPostQueueImpl.setFid(TextUtils.isEmpty(mForumId) ? UserState.getPetInfo().getArray()
                    .get(mPetPostion).getBreedid() : mForumId, mTags,
                    mSplashBannerInfo == null ? "" : mSplashBannerInfo.actid,
                    String.valueOf(Constants.location_lat), String.valueOf(Constants.location_lon),
                    Constants.location_address, locations.name, locations.city);
        } else {
            // TODO 删除宠物时，是User中缓存的宠物信息了？
            mPostQueueImpl.setFid(TextUtils.isEmpty(mForumId) ? UserState.getPetInfo().getArray()
                    .get(mPetPostion).getBreedid() : mForumId, mTags,
                    mSplashBannerInfo == null ? "" : mSplashBannerInfo.actid);
        }

        return list;

    }

    /**
     * 保存至草稿箱
     */
    private void saveToDraft() {
        List<KeyValuePair<String, Integer>> list = preparePostMessage();
        mPostQueueImpl.addQueueToDraft(mPostTitle, mPostContent,
                vRecordVideoView.getVisibility() == View.VISIBLE ? null : list, vRecordVideoView
                        .getVisibility() == View.VISIBLE ? true : false,
                jo == null ? "" : jo.toString(), vShareToSina.isSelected() ? 1 : 0);
        mPostQueueImpl.finishActivity(PostMessageActivity.this);
        mPostQueueImpl.saveToDraft();
        finish();
        // setResult(RESULT_OK);
    }

    private boolean checkInput() {
        if (mPetPostion == -1 && TextUtils.isEmpty(mForumId)) {
            Toast.makeText(getBaseContext(), "请先选择宠物！", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(mPostTitle)) {
            Toast.makeText(getBaseContext(), "标题不能为空！", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (mPostTitle.length() < 6) {
            Toast.makeText(getBaseContext(), "标题长度最小为6个字符", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (mPostTitle.length() > 30) {
            Toast.makeText(getBaseContext(), "标题长度最大为30个字符", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (isFromActivity && mNotePictureAdapter.getDatas().size() == 0) {
            Toast.makeText(getBaseContext(), "参与活动必须上传最少一张照片！", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (mNotePictureAdapter.getDatas().size() > 0) {
            return true;
        } else if (vFunctionVideoInfo.getVisibility() == View.VISIBLE
                || vFunctionQuotePostInfo.getVisibility() == View.VISIBLE) {// 有引用视频或者引用帖子
            return true;
        } else if (TextUtils.isEmpty(mPostContent)) {
            Toast.makeText(getBaseContext(), "帖子内容不能为空！", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }


    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }

    @Override
    protected int getTopBarRightImageViewRes() {
        return R.drawable.button_send_post;
    }

    private void onImageActivity() {
        Intent intent = new Intent(getBaseContext(), ImageFilter2Activity.class);
        intent.putExtra("image", mCameraFilePath);
        startActivityForResult(intent, 111);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PUBLISHPOSTS.CAMERA && resultCode == RESULT_OK) {// 拍照完成
            // onImageActivity();
            handleCameraPhotos(data);
        } else if (requestCode == PUBLISHPOSTS.PHOTOALBUM && resultCode == RESULT_OK) {// 选择照片
            handlePickPhotos(data.getStringArrayListExtra(Constants.PARAM_PHOTO_LIST));
        } else if (requestCode == PUBLISHPOSTS.REQUEST_PICK_VIDEO && resultCode == RESULT_OK) {// 选择视频
            handlePickVideo(data);
        } else if (requestCode == PUBLISHPOSTS.REQUEST_QUOTE_POST && resultCode == RESULT_OK) {// 引用帖子
            handleQuotePost(data);
        } else if (requestCode == PUBLISHPOSTS.REQUEST_QUOTE_FRIEND && resultCode == RESULT_OK) {// @提醒好友
            handleQuoteFriend(data);
        } else if (requestCode == PUBLISHPOSTS.PHOTO_AMEND && resultCode == RESULT_OK) {// 图片修改
            photoAmend(data);
        } else if (requestCode == 111) {
            // handleCameraPhotos(data);
        } else if (requestCode == PUBLISHPOSTS.REQUEST_ADDPET && resultCode == RESULT_OK) {
            initPets();
        } else if (requestCode == BAIDULOATIONRESULT && resultCode == RESULT_OK) {
            locations = (Location) data.getSerializableExtra("location");
            if ("不显示位置".equals(locations.name)) {
                locationText.setText("所在位置");
                image_icon.setBackgroundResource(R.drawable.location_1);
            } else {
                image_icon.setBackgroundResource(R.drawable.location_2);
                if (locations.city != null && !locations.city.equals("")
                        && !locations.city.equals(locations.name)) {
                    locationText.setText(locations.city + "-" + locations.name);
                } else {
                    locationText.setText(locations.name);
                }
            }
        }

        if (null != sharePopupWindow) {
            UMSsoHandler ssoHandler =
                    sharePopupWindow.mController.getConfig().getSsoHandler(requestCode);
            if (ssoHandler != null) {
                ssoHandler.authorizeCallBack(requestCode, resultCode, data);
            }
        }
    }

    private final List<String> mFansUser = new ArrayList<String>();

    private void handleQuoteFriend(Intent data) {
        String temp =
                vContent.getText().toString() + " @"
                        + data.getStringExtra(Constants.KEY_FANS_USERNAME) + "";
        SpannableStringBuilder ssb =
                CommonUtil.convetToHtml(CommonUtil.parseEmoji(temp), PostMessageActivity.this);

        vContent.setText(ssb);
        vContent.setSelection(vContent.getText().length());

        HappyPetApplication.mHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
                // 获取编辑框焦点
                vContent.setFocusable(true);
                showKeyboard();
            }
        }, 150);

        // if (!mFansUser.contains(data.getStringExtra(Constants.KEY_FANS_USERNAME))) {
        // View view = View.inflate(getBaseContext(), R.layout.linear_user_icon, null);
        // ImageView icon = (ImageView) view.findViewById(R.id.icon);
        // ImageLoader.getInstance().displayImage(
        // data.getStringExtra(Constants.KEY_FANS_USERFACE), icon);
        // vUserFaceContainer.addView(view);
        // mFansUser.add(data.getStringExtra(Constants.KEY_FANS_USERNAME));
        // }
    }

    /**
     * 处理帖子引用
     * 
     * @param data
     */
    private void handleQuotePost(Intent data) {
        if (data == null) {
            switchSelect(SWITCHSTATE.NONE);
        } else {
            switchSelect(SWITCHSTATE.POST);
            ImageLoader.getInstance().displayImage(data.getStringExtra(Constants.KEY_POST_COVER),
                    ((ImageView) vFunctionQuotePostInfo.findViewById(R.id.icon)));
            ((TextView) vFunctionQuotePostInfo.findViewById(R.id.title)).setText(data
                    .getStringExtra(Constants.KEY_POST_NAME));
            vFunctionQuotePostInfo.setTag(data);
            vFunctionQuotePostInfo.setOnClickListener(this);
        }
    }

    /**
     * 处理视频引用
     * 
     * @param data
     */
    private void handlePickVideo(Intent data) {
        if (data == null) {
            switchSelect(SWITCHSTATE.NONE);
        } else {
            switchSelect(SWITCHSTATE.VIDEO);
            ImageLoader.getInstance().displayImage(
                    data.getStringExtra(Constants.KEY_VIDEO_IMAGE_URL),
                    ((ImageView) vFunctionVideoInfo.findViewById(R.id.icon)));
            ((TextView) vFunctionVideoInfo.findViewById(R.id.title)).setText(data
                    .getStringExtra(Constants.KEY_VIDEO_NAME));
            vFunctionVideoInfo.setTag(data);
            vFunctionVideoInfo.setOnClickListener(this);
        }

    }

    enum SWITCHSTATE {
        NONE, PHOTO, VIDEO, POST,
        /** 录制的视频 */
        RECORDVIDEO
    }

    private void switchSelect(SWITCHSTATE state) {
        vFunctionContainerView.setVisibility(View.GONE);
        vPictureGridView.setVisibility(View.GONE);
        vFunctionVideoInfo.setVisibility(View.GONE);
        vFunctionQuotePostInfo.setVisibility(View.GONE);
        vRecordVideoView.setVisibility(View.GONE);
        if (state == SWITCHSTATE.NONE) {
            vFunctionContainerView.setVisibility(View.VISIBLE);
        } else if (state == SWITCHSTATE.PHOTO) {
            vPictureGridView.setVisibility(View.VISIBLE);
        } else if (state == SWITCHSTATE.VIDEO) {
            vFunctionVideoInfo.setVisibility(View.VISIBLE);
        } else if (state == SWITCHSTATE.POST) {
            vFunctionQuotePostInfo.setVisibility(View.VISIBLE);
        } else if (state == SWITCHSTATE.RECORDVIDEO) {
            vRecordVideoView.setVisibility(View.VISIBLE);
        }
    }

    private void photoAmend(Intent data) {
        resetAdapter(data.getStringArrayListExtra(Constants.PARAM_PHOTO_LIST));
    }

    private void handleCameraPhotos(Intent data) {
        ArrayList<String> list = mNotePictureAdapter.getDatas();
        list.add(mCameraFilePath);
        // 已经存在的
        List<KeyValuePair<String, Integer>> pairs = new ArrayList<KeyValuePair<String, Integer>>();
        pairs.add(new KeyValuePair<String, Integer>(mCameraFilePath, 0));
        postFiles(pairs);
        resetAdapter(list);
    }

    private void handlePickPhotos(ArrayList<String> list) {
        ArrayList<String> oldList = mNotePictureAdapter.getDatas();

        final ArrayList<KeyValuePair<String, Integer>> needUploadInfos =
                new ArrayList<KeyValuePair<String, Integer>>();
        for (int i = 0; i < list.size(); i++) {
            if (!oldList.contains(list.get(i))) {
                needUploadInfos.add(new KeyValuePair<String, Integer>(list.get(i), 0));
            }
        }
        postFiles(needUploadInfos);
        resetAdapter(list);
    }

    /**
     * 上传文件（支持多张）
     */
    private void postFiles(List<KeyValuePair<String, Integer>> list) {
        mPostQueueImpl.addQueue(list);
    }

    private void resetAdapter(ArrayList<String> picUrList) {
        if (picUrList.size() == 0) {
            mNotePictureAdapter.resetList(picUrList);
            mNotePictureAdapter.notifyDataSetChanged();
            switchSelect(SWITCHSTATE.NONE);
        } else {
            switchSelect(SWITCHSTATE.PHOTO);
            mNotePictureAdapter.resetList(picUrList);
            mNotePictureAdapter.notifyDataSetChanged();
        }
    }

    SharePopupWindow sharePopupWindow;
    private List<TagInfo> mTagList = new ArrayList<TagInfo>();

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.photo_activity:
            case R.id.photo:
                hideKeyBoard();
                showSelectPicPopupWindow();
                break;
            case R.id.video:
                hideKeyBoard();
                quoteVideo();
                break;
            case R.id.quote_post:
                hideKeyBoard();
                quotePost();
                break;
            case R.id.quote_friend:// 标签
                quoteTags();
                break;
            case R.id.video_info:
                showDeleteVideoWindow();
                break;
            case R.id.quote_post_info:
                showDeletePostWindow();
                break;
            case R.id.record_video:
                showDeleteRecordVideoWindow();
                break;
            case R.id.share_to_sina:
                clickShareButton();
                break;
            case R.id.show_faceview:
                if (vFaceContainerView.getVisibility() == View.VISIBLE) {
                    vFaceView.setImageResource(R.drawable.show_faceview);
                } else {
                    vFaceView.setImageResource(R.drawable.showkey);
                    hideKeyBoard();
                }
                HappyPetApplication.mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (vFaceContainerView.getVisibility() == View.VISIBLE) {
                            vFaceContainerView.setVisibility(View.GONE);
                            // 获取编辑框焦点
                            vContent.setFocusable(true);
                            showKeyboard();
                        } else {
                            vFaceContainerView.setVisibility(View.VISIBLE);
                        }
                    }
                }, 300);
                break;
            case R.id.hide_key:
                hideKeyBoard();
                vFaceAllViews.setVisibility(View.GONE);
                vFaceContainerView.setVisibility(View.GONE);
                break;
            case R.id.show_aite:
                hideKeyBoard();
                quoteFriend();
                break;
            case R.id.add_pet:
                Intent intent = new Intent(getBaseContext(), AddPetActivity.class);
                intent.putExtra("petid", "");
                intent.putExtra("petname", "");
                intent.putExtra("petpic", "");
                startActivityForResult(intent, PUBLISHPOSTS.REQUEST_ADDPET);
                break;
            case R.id.voice_input:// 语音输入
                Boolean isShowDialog = MoccaPreferences.Iflytek.get();
                if (isShowDialog) {
                    // 显示听写对话框
                    iatDialog.setListener(recognizerDialogListener);
                    iatDialog.show();
                    // showTip(getString(R.string.text_begin));
                }
                break;
            // case R.id.checkbox:
            // if (checkbox.isChecked()) {
            // locationManager.startLoacation(PostMessageActivity.this,
            // new IRequest<Location>() {
            // @Override
            // public void request(Location t) {
            // location = t;
            // }
            // });
            // // if (CommonUtil.isNetworkAvailable(this) != 0) {
            // locationManager.InitLocation();
            // // }
            // } else {
            // locationManager.stopLocation();
            // }
            // break;
            case R.id.showLocation:// 显示当前位置
                Intent intent2 = new Intent(PostMessageActivity.this, NearLoationActivity.class);
                if (locations == null) {
                    intent2.putExtra("locationName", "不显示位置");
                } else {
                    intent2.putExtra("locationName", TextUtils.isEmpty(locations.name) ? "不显示位置"
                            : locations.name);
                }
                startActivityForResult(intent2, BAIDULOATIONRESULT);

                // if (checkbox.isChecked()) {
                // checkbox.setChecked(false);
                // locationManager.stopLocation();
                // } else {
                // checkbox.setChecked(true);
                // locationManager.startLoacation(PostMessageActivity.this,
                // new IRequest<Location>() {
                // @Override
                // public void request(Location t) {
                // location = t;
                // }
                // });
                // // if (CommonUtil.isNetworkAvailable(this) != 0) {
                // locationManager.InitLocation();
                // // }
                // }
                break;
            default:
                break;
        }
    }

    /**
     * 听写UI监听器
     */
    private final RecognizerDialogListener recognizerDialogListener =
            new RecognizerDialogListener() {
                @Override
                public void onResult(RecognizerResult results, boolean isLast) {
                    String text = JsonParser.parseIatResult(results.getResultString());
                    vContent.append(text);
                    vContent.setSelection(vContent.length());
                }

                @Override
                public void onError(SpeechError error) {
                    Toast.makeText(getBaseContext(), error.getPlainDescription(true),
                            Toast.LENGTH_SHORT).show();
                }
            };

    /**
     * 初始化监听器。
     */
    private final InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            // Log.d(TAG, "SpeechRecognizer init() code = " + code);
            // if (code != ErrorCode.SUCCESS) {
            // showTip("初始化失败,错误码：" + code);
            // }
        }
    };


    SelectTagDialog dialog;

    private void resetTags(List<TagInfo> t) {
        vTagsContainer.removeAllViewsInLayout();
        vTagsContainer.removeAllViews();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < t.size(); i++) {
            if (i == 0) {
                sb.append(t.get(i).tagid);
            } else {
                sb.append("," + t.get(i).tagid);
            }
        }

        StringBuffer nameSb = new StringBuffer();
        for (int i = 0; i < t.size(); i++) {
            if (i == 0) {
                nameSb.append(t.get(i).tagname);
            } else {
                nameSb.append("," + t.get(i).tagname);
            }

            View view = View.inflate(getBaseContext(), R.layout.item_quote_tag, null);
            ((TextView) view.findViewById(R.id.tag)).setText(t.get(i).tagname);
            vTagsContainer.addView(view);
        }
        // if (t.size() == 0) {
        // vTags.setText("添加标签");
        // } else {
        // vTags.setText("标签：" + nameSb.toString());
        // }
        mTags = sb.toString();
    }

    private void quoteTags() {
        if (null != mTagInfos) {
            hideKeyBoard();
            if (dialog == null) {
                dialog =
                        new SelectTagDialog(PostMessageActivity.this, R.style.Edit_Count_Dialog,
                                mTagInfos, mTagList, new IRequest<List<TagInfo>>() {

                                    @Override
                                    public void request(List<TagInfo> t) {
                                        if (t != null) {
                                            mTagList = t;
                                            resetTags(t);
                                        }
                                    }
                                });
            }
            dialog.show();
        }
    }

    private void showKeyboard() {
        // 打开软键盘
        InputMethodManager imm =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    private void clickShareButton() {
        if (vShareToSina.isSelected()) {
            MoccaPreferences.SINA_WEIBO_LOGIN_STATE.put(false);
            vShareToSina.setSelected(false);
        } else {
            sharePopupWindow = new SharePopupWindow();
            if (!sharePopupWindow.isAuthenticatedBySina(this)) {
                sharePopupWindow.authSinaWeibo(this, new IRequest<Boolean>() {

                    @Override
                    public void request(Boolean t) {
                        if (t) {
                            MoccaPreferences.SINA_WEIBO_LOGIN_STATE.put(true);
                            vShareToSina.setSelected(true);
                        } else {
                            MoccaPreferences.SINA_WEIBO_LOGIN_STATE.put(false);
                            vShareToSina.setSelected(false);
                        }
                    }
                });
            } else {
                MoccaPreferences.SINA_WEIBO_LOGIN_STATE.put(true);
                vShareToSina.setSelected(true);
            }
        }
    }

    private void quotePost() {
        startActivityForResult(new Intent(this, QuotePostActivity.class),
                PUBLISHPOSTS.REQUEST_QUOTE_POST);
    }

    private void quoteFriend() {
        if (mFansUser.size() == 5) {
            Toast.makeText(getBaseContext(), "只可以@5个人", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(this, QuoteFriendActivity.class);
        intent.putExtra(Constants.KEY_GROUP_FID, mForumId);
        startActivityForResult(intent, PUBLISHPOSTS.REQUEST_QUOTE_FRIEND);
    }

    private void quoteVideo() {
        showQuoteVideoPopupWindow();
    }

    /**
     * 拍照
     */
    private void takePhoto() {
        mCameraFilePath =
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/happypet/pic"
                        + File.separator + System.currentTimeMillis() + ".jpg";
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
        startActivityForResult(intent, PUBLISHPOSTS.CAMERA);

        // Intent intent = new Intent(PostMessageActivity.this, CameraActivity.class);
        // intent.putExtra("outputFile", mCameraFilePath);
        // startActivityForResult(intent, PUBLISHPOSTS.CAMERA);
    }

    private void showQuoteVideoPopupWindow() {
        final SelectPicPopupWindow popupWindow = new SelectPicPopupWindow(this);
        View view = View.inflate(getBaseContext(), R.layout.layout_quote_video, null);
        // view.setBackgroundColor(getResources().getColor(R.color.white));
        CommonUtil.addScreenBg(popupWindow, PostMessageActivity.this);
        View recordVideo = view.findViewById(R.id.btn_record_video);
        recordVideo.setVisibility(View.VISIBLE);
        recordVideo.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(getBaseContext(), MediaRecorderActivity.class);
                startActivity(intent);
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.btn_youku).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(getBaseContext(), QuoteVideoActivity.class);
                intent.putExtra(Constants.KEY_VIDEO_TYPE, VIDEO_TYPE.YOUKU.ordinal());
                startActivityForResult(intent, Constants.PUBLISHPOSTS.REQUEST_PICK_VIDEO);
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.btn_tudou).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(getBaseContext(), QuoteVideoActivity.class);
                intent.putExtra(Constants.KEY_VIDEO_TYPE, VIDEO_TYPE.TUDOU.ordinal());
                startActivityForResult(intent, Constants.PUBLISHPOSTS.REQUEST_PICK_VIDEO);
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();
            }
        });
        popupWindow.init(view).showAtLocation(findViewById(R.id.send_post),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void showSelectPicPopupWindow() {
        final SelectPicPopupWindow popupWindow = new SelectPicPopupWindow(this);
        View view = View.inflate(getBaseContext(), R.layout.function_list_layout, null);
        // view.setBackgroundColor(getResources().getColor(R.color.white));
        CommonUtil.addScreenBg(popupWindow, PostMessageActivity.this);
        view.findViewById(R.id.btn_take_photo).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (mNotePictureAdapter.getDatas().size() == Constants.PUBLISHPOSTS_COUNTS) {
                    Toast.makeText(getBaseContext(),
                            String.format("最多选择%s张图片", Constants.PUBLISHPOSTS_COUNTS),
                            Toast.LENGTH_SHORT).show();
                } else {
                    takePhoto();
                }
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.btn_pick_photo).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(getBaseContext(), PictureListActivity.class);
                // 传递当前已经选择的图片
                intent.putStringArrayListExtra(Constants.PARAM_PHOTO_LIST,
                        mNotePictureAdapter.getDatas());
                startActivityForResult(intent, PUBLISHPOSTS.PHOTOALBUM);
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();
            }
        });
        popupWindow.init(view).showAtLocation(findViewById(R.id.send_post),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 删除帖子
     */
    private void showDeletePostWindow() {
        final SelectPicPopupWindow popupWindow = new SelectPicPopupWindow(this);
        View view = View.inflate(getBaseContext(), R.layout.pop_delete_video, null);
        // view.setBackgroundColor(getResources().getColor(R.color.white));
        CommonUtil.addScreenBg(popupWindow, PostMessageActivity.this);
        ((TextView) view.findViewById(R.id.btn_choose_video)).setText("引用帖子");
        view.findViewById(R.id.btn_choose_video).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                quotePost();
            }
        });
        view.findViewById(R.id.btn_delete).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                switchSelect(SWITCHSTATE.NONE);
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();
            }
        });
        popupWindow.init(view).showAtLocation(findViewById(R.id.send_post),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 删除录制的视频
     */
    private void showDeleteRecordVideoWindow() {
        final SelectPicPopupWindow popupWindow = new SelectPicPopupWindow(this);
        View view = View.inflate(getBaseContext(), R.layout.pop_delete_record_video, null);
        // view.setBackgroundColor(getResources().getColor(R.color.white));
        CommonUtil.addScreenBg(popupWindow, PostMessageActivity.this);
        view.findViewById(R.id.btn_delete).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                switchSelect(SWITCHSTATE.NONE);
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();
            }
        });
        popupWindow.init(view).showAtLocation(findViewById(R.id.send_post),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 删除视频
     */
    private void showDeleteVideoWindow() {
        final SelectPicPopupWindow popupWindow = new SelectPicPopupWindow(this);
        View view = View.inflate(getBaseContext(), R.layout.pop_delete_video, null);
        // view.setBackgroundColor(getResources().getColor(R.color.white));
        CommonUtil.addScreenBg(popupWindow, PostMessageActivity.this);
        view.findViewById(R.id.btn_choose_video).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();

                quoteVideo();
            }
        });
        view.findViewById(R.id.btn_delete).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                switchSelect(SWITCHSTATE.NONE);
                popupWindow.dismiss();
            }
        });
        view.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                popupWindow.dismiss();
            }
        });
        popupWindow.init(view).showAtLocation(findViewById(R.id.send_post),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /**
     * 选择图片
     * 
     * @author xindaoapp
     * 
     */
    public class SelectPicPopupWindow extends PopupWindow {

        private final Activity context;

        public SelectPicPopupWindow(Activity context) {
            super(context);
            this.context = context;
        }

        public SelectPicPopupWindow init(View view) {
            this.setContentView(view);
            this.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
            this.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
            this.setFocusable(true);
            this.setAnimationStyle(R.style.PopupAnimation);
            this.setBackgroundDrawable(new ColorDrawable(context.getResources().getColor(
                    R.color.transparent)));
            setFocusable(true);
            return this;
        }

    }

    /** 初始化表情 */
    private void initFaceView() {
        vPlanPoint.removeAllViews();
        for (int i = 0; i < 4; i++) {
            // 添加点view对象
            View view = new View(getBaseContext());
            view.setBackgroundDrawable(getResources().getDrawable(
                    R.drawable.point_background_postmessage));
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(15, 15);
            lp.leftMargin = 10;
            view.setLayoutParams(lp);
            view.setEnabled(false);
            vPlanPoint.addView(view);
        }
        vViewPager.setAdapter(mPagerAdapter);
        vViewPager.setOnPageChangeListener(mFacePageChangeListener);
        vPlanPoint.getChildAt(0).setEnabled(true);
    }

    private final OnPageChangeListener mFacePageChangeListener = new OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0) {
            for (int i = 0; i < vPlanPoint.getChildCount(); i++) {
                if (arg0 == i) {
                    vPlanPoint.getChildAt(i).setEnabled(true);
                } else {
                    vPlanPoint.getChildAt(i).setEnabled(false);
                }
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {}

        @Override
        public void onPageScrollStateChanged(int arg0) {}
    };

    // 填充ViewPager的数据适配器
    private final PagerAdapter mPagerAdapter = new PagerAdapter() {
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public int getCount() {
            return 4;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        private int[] getImgs(int position) {
            switch (position) {
                case 0:
                    return Expressions.expressionImgs0;
                case 1:
                    return Expressions.expressionImgs1;
                case 2:
                    return Expressions.expressionImgs2;
                case 3:
                    return Expressions.expressionImgs3;
                default:
                    return null;
            }
        }

        private String[] getImgNames(int position) {
            switch (position) {
                case 0:
                    return Expressions.expressionImgNames0;
                case 1:
                    return Expressions.expressionImgNames1;
                case 2:
                    return Expressions.expressionImgNames2;
                case 3:
                    return Expressions.expressionImgNames3;
                default:
                    return null;
            }
        }

        @Override
        public Object instantiateItem(View container, int position) {
            View view = View.inflate(getBaseContext(), R.layout.layout_post_face, null);
            GridView gridView = (GridView) view.findViewById(R.id.gridview);
            final int[] images = getImgs(position);
            final String[] imageNames = getImgNames(position);
            FaceAdapter adapter = new FaceAdapter(images);
            gridView.setAdapter(adapter);
            gridView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                    Bitmap bitmap = null;
                    bitmap =
                            BitmapFactory.decodeResource(getResources(), images[position
                                    % images.length]);
                    ImageSpan imageSpan = new ImageSpan(getBaseContext(), bitmap);
                    SpannableString spannableString =
                            new SpannableString(imageNames[position].substring(1,
                                    imageNames[position].length() - 1));
                    spannableString.setSpan(imageSpan, 0, imageNames[position].length() - 2,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    // // 编辑框设置数据
                    String str = vContent.getText().toString();
                    str = CommonUtil.replaceAllKuoHao(str);
                    String emojicon = str + imageNames[position];
                    SpannableStringBuilder ssb =
                            CommonUtil.convetToHtml(CommonUtil.parseEmoji(emojicon),
                                    PostMessageActivity.this);

                    vContent.setText(ssb);
                    vContent.setSelection(vContent.getText().length());
                }
            });
            ((ViewPager) container).addView(view);
            return view;
        }
    };
    private TextView locationText;
    private Location locations;
    private ImageView image_icon;


    class FaceAdapter extends BaseAdapter {
        private final int[] list;

        public FaceAdapter(int[] list) {
            super();
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(getBaseContext(), R.layout.singleexpression, null);
                holder = new ViewHolder();
                holder.icon = (ImageView) convertView.findViewById(R.id.image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.icon.setImageResource(list[position]);
            LinearLayout.LayoutParams params =
                    new LinearLayout.LayoutParams(CommonUtil.dip2px(getBaseContext(), 170) / 3,
                            CommonUtil.dip2px(getBaseContext(), 170) / 3);
            holder.icon.setLayoutParams(params);
            return convertView;
        }

        class ViewHolder {
            ImageView icon;
        }

    }

    /**
     * 录制视频结束
     * 
     * @author xindaoapp
     * 
     */
    class RecordVideoReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String path = intent.getStringExtra("video_path");
            String coverPath = intent.getStringExtra("video_cover_path");

            ImageLoader.getInstance().displayImage("file://" + coverPath,
                    (ImageView) vRecordVideoView.findViewById(R.id.icon));

            switchSelect(SWITCHSTATE.RECORDVIDEO);

            mPostQueueImpl.addQueue(new KeyValuePair<String, Integer>(path, 1), coverPath);
        }

    }


    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // 如果发送过信息，则不保存草稿
                if (isPostMessage)
                    finish();
                else
                    showDialogToSaveDraft();
            }
        };
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 如果发送过信息，则不保存草稿
            if (isPostMessage) {
                return super.onKeyDown(keyCode, event);
            } else {
                showDialogToSaveDraft();
                return true;
            }
        } else if (keyCode == KeyEvent.KEYCODE_HOME) {
            Toast.makeText(PostMessageActivity.this, "点击了home键", 1).show();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showDialogToSaveDraft() {
        // 标题或者内容不为空，提示存草稿箱
        if (!TextUtils.isEmpty(mPostTitle) || !TextUtils.isEmpty(mPostContent)) {
            new AlertDialog.Builder(PostMessageActivity.this).setTitle("保存到草稿箱吗？")
                    .setNegativeButton("保存", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            saveToDraft();
                        }
                    }).setPositiveButton("放弃", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            PostMessageActivity.this.finish();
                        }
                    }).setCancelable(true).show();
        } else {
            PostMessageActivity.this.finish();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

}
